<template>
    <div class="advertisement" style="background-color:#ffffff;border-radius:8px;padding:20px;margin-top:30px">
        <div class="advertisement-layout">
            <el-form ref="advertisementRef" :model="form" :rules="rules" label-width="auto">
                <el-form-item label="广告名称:" prop="adsName">
                    <el-input v-model="form.adsName" placeholder="请输入广告名称" style="width: 50%"
                        @focus="advertisementLimit.nameLimit = true" @blur="advertisementLimit.nameLimit = false"
                        :show-word-limit="advertisementLimit.nameLimit" maxlength="30" />
                </el-form-item>
                <el-form-item label="广告位置:" prop="advLocation">
                    <dict-tag :options="adv_location" :value="form.advLocation" />
                </el-form-item>
                <el-form-item label="展示形式:" style="width: 50%" v-if="form.advLocation!=0">
                    <el-select @change="advertisementTypeChange" v-model="advertisementType" placeholder="请选择轮播形式"
                        size="large" style="width: 100%">
                        <el-option v-for="item in advertisementTypeSel" :key="item.id" :label="item.label"
                            :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="广告状态:" prop="status">
                    <el-switch v-model="form.status" inline-prompt active-text="启用" inactive-text="禁用" active-value="1"
                        inactive-value="0" />
                </el-form-item>
                <el-form-item>
                    <el-table :data="tableData" style="width: 100%">
                        <el-table-column prop="orderNum" label="轮播顺序" align="center">
                            <template #default="scope">
                                <el-input-number :disabled="advertisementType === 2 ? false : true"
                                    v-model="scope.row.orderNum" :min="1" :max="5" placeholder="请输入轮播顺序" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="imgId" label="广告图片" align="center">
                            <template #default="scope">
                                <image-upload v-model="scope.row.imgId" :limit="1"></image-upload>
                            </template>
                        </el-table-column>
                        <el-table-column prop="campaignPageId" label="跳转活动名称" align="center">
                            <template #default="scope">
                                <el-select v-model="scope.row.campaignPageId" placeholder="请选择轮播形式" size="large"
                                    style="width: 100%">
                                    <el-option v-for="item in activeListSel" :key="item.campaignPageId"
                                        :label="item.campaignPageName" :value="item.campaignPageId" />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="100" align="center" v-if="advertisementType === 2">
                            <template #default="scope">
                                <el-button link type="primary" size="small" @click.prevent="deleteRow(scope.$index)">
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-button v-if="advertisementType === 2 && form.advLocation != '0'" class="mt-4"
                        style="width: 100%;margin-top:10px;" type="primary" @click="onAddItem">添加多个广告位(最多5个)</el-button>
                </el-form-item>
            </el-form>
            <div class="footer-btn">
                <div class="dialog-footer">
                    <el-button type="primary" size="small" @click="submit">提 交</el-button>
                    <el-button size="small" @click="goBack">返 回</el-button>
                </div>
            </div>
        </div>

    </div>
</template>
<script setup>
import { getAds, addAds, updateAds, listCampaignPage } from "@/api/decor/advertisement";
const { proxy } = getCurrentInstance();
const { adv_location } = proxy.useDict('adv_location')
const router = useRouter();
const route = useRoute();
const advertisementTypeSel = ref([
    { id: 1, label: '单图固定' },
    { id: 2, label: '多图轮播' },
])
let advertisementType = ref(1)
const advertisementLimit = ref({
    nameLimit: false,
})
const data = reactive({
    form: {
        advLocation: route.params.origin,
    },
});
const { form } = toRefs(data);
const tableData = ref([{ orderNum: 1, imgId: '', campaignPageId: '' }])
const activeListSel = ref([])
const rules = ref({
    adsName: [
        { required: true, message: "请输入广告名称", trigger: "change" },
    ],
    status: [{ required: true, message: "请选择广告状态", trigger: "blur" }],
})
// 获取所有的活动名称
const getActiveList = () => {
    listCampaignPage({ status: "1" }).then((res) => {
        activeListSel.value = [{campaignPageId:-1,campaignPageName:'无'},...res.rows]
    })
};
// 获取数据详情
(() => {
    const adsId = route.params.adsId
    if (adsId) {
        getAds(adsId).then((response) => {
            form.value = response.data
            advertisementType.value = response.data.adDetailsList.length < 2 ? 1 : 2
            if (response.data.adDetailsList.length === 0) {
                tableData.value = [{ orderNum: 1, imgId: '', campaignPageId: '' }]
                advertisementType.value = 1
            } else {
                tableData.value = response.data.adDetailsList
            }
        })
    }
})();
// 轮播形式发生改变
const advertisementTypeChange = () => {
    if (advertisementType.value === 1) {
        tableData.value = [{ orderNum: 1, imgId: '', campaignPageId: '' }]
    }
}
// 多图轮播删除
const deleteRow = (index) => {
    tableData.value.splice(index, 1)
}
// 多图轮播新增
const onAddItem = () => {
    if (tableData.value.length < 5) {
        tableData.value.push({
            orderNum: tableData.value.length + 1, imgId: '', campaignPageId: ''
        })
    } else {
        proxy.$modal.msgError("最多添加5个广告位");
    }

}
// 提交
const submit = () => {
    proxy.$refs["advertisementRef"].validate((valid) => {
        if (valid) {
            if (tableData.value.length === 0) {
                proxy.$modal.msgError("至少应添加一条广告位");
                return
            }
            // 是否存在相同的orderNum
            const hasDuplicateSort = tableData.value.some((item, index) => tableData.value.findIndex(obj => obj.orderNum === item.orderNum) !== index);
            // imgId是否为空
            const hasEmptyAdvImg = tableData.value.some(item => item.imgId === '' || item.imgId === null);
            if (hasDuplicateSort === true) {
                proxy.$modal.msgError("不允许存在相同的轮播顺序");
            } else {
                if (hasEmptyAdvImg === true) {
                    proxy.$modal.msgError("存在未上传的广告图片");
                } else {
                    if (form.value.adsId) {
                        const data = {
                            decorAdDetailsBoList: tableData.value,
                            decorAdsBo: form.value,
                            isUpdateStatus: false
                        }
                        updateAds(data).then((res) => {
                            proxy.$modal.msgSuccess("修改成功");
                            router.go(-1)

                        })
                    } else {
                        const data = {
                            decorAdDetailsBoList: tableData.value,
                            decorAdsBo: form.value,
                            isUpdateStatus: false
                        }
                        addAds(data).then((res) => {
                            proxy.$modal.msgSuccess("新增成功");
                            router.go(-1)
                            form.value = ''
                            tableData.value = [{ orderNum: 1, imgId: '', campaignPageId: '' }]
                        })
                    }
                }
            }

        }else{
            proxy.$modal.msgError('请根据提示完善必填信息')
        }
    })
}
const goBack = () => {
    router.go(-1)
}
getActiveList()
</script>